<template>
  <v-container fluid>
    <v-row class="funcArea">
      <v-col cols="4">
        <v-text-field
          :label="label"
        />
      </v-col>
      <v-col cols="8" class="text-right">
        
        <el-button type="primary" :plain="true" @click="saveMindMap">保存</el-button>
        <el-button type="primary" style="margin-left: 16px" @click="isShowSideBar = !isShowSideBar" plain>工具栏</el-button>
        
      </v-col>
    </v-row>
    <v-row>
      <v-col cols="14">
        <div id="mind" >
			<div class="sideBar"  v-if="isShowSideBar">
				
				<el-row>
					<div class="t-title">
						<span >操作</span>
					</div>
					<el-row>
						<el-button type="primary" @click="exportAsImage" plain>导出图片</el-button>
						<el-button type="primary" @click="exportAsFile" plain>导出文件</el-button>
					</el-row>
				</el-row>
				<el-row>
					<div class="t-title">
						<span >图标</span>
					</div>
					<el-row class="t-content t-icon">
						<el-button @click="optNode('icons', '', true)">清空图标</el-button>
						<el-button @click="optNode('icons','✅')" type="success" :icon="Check" circle></el-button>
						<el-button @click="optNode('icons','❌')" type="danger"  :icon="Close" circle></el-button>
						
					</el-row>
				</el-row>
				
				<el-row>
					<el-divider />
					<div class="t-title">
						<span >标签</span>
					</div>
					<el-row class="t-content t-tag">
						<el-button @click="optNode('tags', '', true)">清空标签</el-button>
						<el-button @click="optNode('tags','ignore')" type="warning" plain>ignore</el-button>
						<el-button type="success" @click="optNode('tags','通过')">通过</el-button>
						<el-button type="warning" @click="optNode('tags','失败')">失败</el-button>
						<el-button type="danger" @click="optNode('tags','阻塞')">阻塞</el-button>
					</el-row>
				</el-row>

				<el-row>
					<el-divider />
					<div class="t-title">
						<span>主题</span>
					</div>
					<el-row>
						<el-button type="primary" @click="switchTheme" plain>切换主题</el-button>
					</el-row>
				</el-row>
			</div>
		</div>
        <!-- <textarea v-model="jsonData" style="width: 100%; height: 100px; margin-top: 20px;"></textarea> -->
      </v-col>
    </v-row>
  </v-container>
</template>


<script setup>
import JSZip from 'jszip'
import { getMindById, updateMind, createMind } from '@/api'
import MindElixir from 'mind-elixir'
import { ElMessage, ElNotification } from 'element-plus'
import { ref,onMounted, onBeforeUnmount, reactive } from 'vue'
import { useStore } from 'vuex'
import { changeIsCreateGroup, changeCommonId } from '@/assets/js/common'
import { Check, Close } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

let router = useRouter()
let isShowSideBar = ref(false)
let store = useStore()
let drawer = ref(false)
let ME = null
let jsonData = ref(null)
let label = ref("")
let theme = ref({
	"name": "Latte",
	"type": "light",
	"palette": ["#336699"],
	"cssVar": {
	"--gap": "30px",
	"--main-color": "#444446",
	"--main-bgcolor": "#ffffff",
	"--color": "#777777",
	"--bgcolor": "#f6f6f6",
	"--panel-color": "#444446",
	"--panel-bgcolor": "#ffffff",
	"--panel-border-color": "#eaeaea"
	}
})

// 添加一个ref来存储上一次保存的数据快照
let lastSavedData = ref(null)

onMounted (() => {
	ME = new MindElixir(getMindmapOptions("#mind", theme.value))
	if (store.getters.getIsCreateGroup) {
		initMindMap()
	} else {
		fetchMindMap()
	}

	// 首次加载数据时保存文件快照
	lastSavedData.value = JSON.stringify(ME.getData())

	// 添加鼠标失焦自动保存功能
	document.addEventListener('mouseleave', handleAutoSave)
})
onBeforeUnmount(() => {
	if (ME) {
		ME = null
		jsonData.value = null
		lastSavedData.value = null
	}
	// 移除鼠标失焦自动保存功能
	document.removeEventListener('mouseleave', handleAutoSave)
	
})


function optNodeWithKey(node, k, v, del=false){
	// console.log("sns's item:", node.topic)
	// 如果需要添加的key不在node中，则将key添加到节点中去
	if (!(k in node)){
	node[k] = []
	}
	// 如果del为true,则清空已添加的所有key
	if (del){
	console.log("清除", k)
	node[k] = []
	} else {
	// 如果tag已存在则忽略，不存在时添加
	if (!node[k].includes(v)){

		console.log("添加", k, v)
		node[k].push(v)
	}
	}
}
// 操作节点，添加和清除；可操作项：tags、icons
function optNode(k, v, del=false) {
	// 获取当前操作节点
	// const selectedNode = this.ME.currentNode == null ? this.ME.currentNodes : this.ME.currentNode.nodeObj
	if (ME.currentNodes){
		const sns = ME.currentNodes
		for (var i=0; i<sns.length; i++){
			optNodeWithKey(sns[i].nodeObj, k, v, del)
		}
	} else if(ME.currentNode) {
		optNodeWithKey(ME.currentNode.nodeObj, k, v, del)
	} else {
		ElMessage({
			type: "Info",
			message: "未找到要操作的节点"
		})
	}
	ME.refresh()
}

// 获取初始化配置
function getMindmapOptions(el, theme){
	return {
		el: el,
		direction: MindElixir.RIGHT,
		draggable: store.getters.getOptions.draggable,
		editable: store.getters.getOptions.editable,
		// editable: false,
		contextMenu: store.getters.getOptions.contextMenu,
		// contextMenu: false,
		toolBar: store.getters.getOptions.toolBar,
		// toolBar: false,
		nodeMenu: store.getters.getOptions.nodeMenu,
		keypress: store.getters.getOptions.keypress,
		allowUndo: store.getters.getOptions.allowUndo,
		locale: "zh_CN",
		theme: theme,
	}
}
// 查看已存在数据
function fetchMindMap(){
	try {
	// 获取mind数据并展示；如果数据不符合展示格式给出
	getMindById(store.getters.getCommonId).then((res)=>{
		label.value = res.data.title
		jsonData.value = JSON.parse(res.data.content)
		
		// 初始化主题
		// jsonData.value.theme = theme.value
		console.log("inited data:", jsonData.value)
		// 渲染数据
		ME.init(jsonData.value)
		
		// 首次加载数据时保存文件快照，避免自动保存的触发
        lastSavedData.value = JSON.stringify(ME.getData())
	})
	} catch (error) {
	console.error('Error fetching mindmap:', error)
	}
} 

// 初始化并渲染数据
function initMindMap() {
	// 初始化mindmap
	
	// 如果数据为新，则调用初始化方法
	if (store.getters.getIsCreateGroup) {
		console.log("进入创建数据逻辑")
		jsonData.value = MindElixir.new("中心主题");
		label.value = jsonData.value.nodeData.topic
		ME.init(jsonData.value)

	} else {
		console.log("进入更新数据逻辑")
		ME.init(jsonData.value);
	}
	
	// 初始化完成后，保存文件快照
	lastSavedData.value = JSON.stringify(ME.getData())
}

// 处理鼠标失焦自动保存
function handleAutoSave() {
    // 检查是否有思维导图数据需要保存
    if (ME && ME.getData()) {
        // 获取当前思维导图数据的JSON字符串表示
        const currentDataStr = JSON.stringify(ME.getData())
        
        // 检查数据是否发生变化
        if (currentDataStr !== lastSavedData.value) {
            saveMindMap()
            // 更新上一次保存的数据快照
            lastSavedData.value = currentDataStr
        }
    }
}

// 保存数据
function saveMindMap(){
	try {
		// 先获取当前数据
		let contentData = ME.getData()
		jsonData.value = JSON.stringify(contentData, null , 0)
		let id = store.getters.getCommonId.id
		let title = contentData.nodeData.topic
	
		if (store.getters.getIsCreateGroup) {
			// 新增数据
			createMind({
			title: title,
			content: jsonData.value,
			format: '',
			create_by: store.getters.getCurUser,
			}).then((res)=>{
				// 新增成功后，更新commonId并跳转编辑页面
				if (res && res.data && res.data.id) {
					changeCommonId(res.data.id)
					router.push({name: 'mindEdit', params: {id: res.data.id}})	
				}
			})
			ElMessage({
				message: '保存成功',
				type: "success"
			})
			changeIsCreateGroup(false)
		} else {
			// 更新数据
			updateMind({
			id: id,
			title: title,
			content: jsonData.value,
			format: '',
			is_deleted: 0,
			update_time: "",
			update_by: store.getters.getCurUser,
			})
			console.log("更新数据")

			ElMessage({
				message: '保存成功',
				type: "success"
			})
		}

		// 数据快照更新
        lastSavedData.value = JSON.stringify(ME.getData())
	} catch (error) {
	console.error('Error saving mindmap:', error)
	}
} 

// 导出图片
function exportAsImage(){
	try {
	const contentData = ME.getData()
	const a = document.createElement('a')
	// a.href = URL.createObjectURL(await this.ME.exportPng(false, style + katex))
	ME.exportPng(false).then((res)=>{
		a.href = URL.createObjectURL(res)
		a.download = contentData.nodeData.topic + ".png"
		a.click()
	})
	// URL.revokeObjectURL(url)
	} catch (e) {
	console.log(e)
	} 
}

// 导入为文件
function exportAsFile(){
	// todolist
	console.log("导出为文件")
}

// 切换主题
function switchTheme(){
	let curTheme = jsonData.value.theme
	// if (curTheme.type == 'dark'){
	// 	curTheme.type = 'light'
	// } else {
	// 	curTheme.type = 'dark'
	// }

	// 线条颜色
	curTheme.palette = ['#33cc99']  // arrayList ['#fff']
	console.log('switch theme', curTheme)
	ME.init(jsonData.value)
}

</script>


<style scoped>
.funcArea {
  margin: 35px 0px 0px -12px;
  height: 59px;
}

#mind {
  width: auto;
  height: 85vh;
  margin: -15px 0px 0px 0px;
  overflow: hidden;
}
.sideBar {
	width: 300px;
	height: 100%;
	position: absolute;
	border: 0.1px solid #e4e7e9;
	background-color: #e5edf4;
	top: 0;
	right: 0;
	padding: 8px;
	animation: sideShow 0.5s;
}
.t-title {
	font-size: 16px;
	font-weight: bold;
	text-align: left;
	margin: 10px;
	width: 200px;
}
.t-content .el-button {
	margin: 5px;
}
.t-tag .el-button  {
	color: #464646;
}

@keyframes sideShow{
	0% {
		right: -300px;
	}
	100% {
		right: 0px;
	}
}


</style>